package com.victor.controller.web;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.victor.entity.Age;
import com.victor.entity.Category;
import com.victor.entity.Copyright;
import com.victor.entity.PicturePath;
import com.victor.entity.Picturebook;
import com.victor.entity.Series;
import com.victor.entity.Seriesandpicbook;
import com.victor.service.CategoryService;
import com.victor.service.PicturePathService;
import com.victor.service.PicturebookService;
import com.victor.service.SeriesService;
import com.victor.service.SeriesandpicbookService;
import com.victor.utils.FileUpload;
import com.victor.utils.Msg;

@RestController
@RequestMapping("/audio")
public class AudioController {

	@Autowired
	private PicturebookService picService;

	@Autowired
	private SeriesService seriesService;

	@Autowired
	private SeriesandpicbookService sapService;

	@Autowired
	private PlatformTransactionManager txManager;

	@Autowired
	private CategoryService categoryService;

	@Autowired
	private PicturePathService pathService;

	/**
	 * 新增音频
	 * 
	 * @param file
	 * @param photo
	 * @param picture
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@PostMapping("/saveAudio")
	public Msg saveAudio(MultipartFile photo, Picturebook picture, int[] pathids, HttpServletRequest request)
			throws Exception {
		// 1.保存封面
		if (photo != null && !photo.isEmpty()) {
			String photoPath = FileUpload.uploadFile(photo, request, "photo");
			picture.setPCoverPhoto(photoPath);
		}

		// 3.保存
		picture.setPType("2");
		boolean bool = picService.insertPicture(picture);
		if (!bool) {
			return Msg.fail();
		}

		// 根据 pathids 修改路径信息
		bool = pathService.setPidToPath(pathids, picture.getPId());
		if (!bool) {
			return Msg.fail();
		}

		return Msg.success().add("id", picture.getPId());
	}

	/**
	 * 获取音频详情
	 * 
	 * @param id
	 * @return
	 */
	@GetMapping("/getAudio/{pid}")
	public Msg getAudio(@PathVariable("pid") Integer id) {
		Picturebook findById = picService.findById(id);
		List<PicturePath> pathList = pathService.findByPid(id);
		return Msg.success().add("audio", findById).add("path", pathList);
	}

	/**
	 * 修改音频
	 * 
	 * @param file
	 * @param photo
	 * @param picture
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@PostMapping("/updateAudio")
	public Msg updateAudio(MultipartFile file, MultipartFile photo, Picturebook picture, int[] pathids,
			HttpServletRequest request) throws Exception {
		// 1.保存封面
		if (photo != null && !photo.isEmpty()) {
			String photoPath = FileUpload.uploadFile(photo, request, "photo");
			picture.setPCoverPhoto(photoPath);
		}

		// 2.保存文件
		if (file != null && !file.isEmpty()) {
			String filePath = FileUpload.uploadFile(file, request, "picture");
			picture.setPVideoPath(filePath);
		}

		// 3.保存
		boolean bool = picService.update(picture);

		// 根据 pathids 修改路径信息
		if (pathids != null && pathids.length > 0) {
			bool = pathService.setPidToPath(pathids, picture.getPId());
		}
		if (!bool) {
			return Msg.fail();
		}
		return Msg.success();
	}

	/**
	 * 新增音频系列信息
	 * 
	 * @param photo
	 * @param series
	 * @param pictureIds
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@PostMapping("/saveSeries")
	public Msg saveSeries(MultipartFile photo, Series series, int[] audioIds, HttpServletRequest request)
			throws Exception {
		series.setSType("2");
		if (photo != null && !photo.isEmpty()) {
			String photoPath = FileUpload.uploadFile(photo, request, "photo");
			series.setSCoverPhoto(photoPath);
		}
		boolean bool = seriesService.saveSeries(series, audioIds);
		return Msg.judge(bool);
	}

	/**
	 * 修改音频系列信息
	 * 
	 * @param series
	 * @param photo
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@PostMapping("/updateSeries")
	public Msg updateSeries(Series series, MultipartFile photo, HttpServletRequest request, int[] audioIds)
			throws Exception {
		if (photo != null && !photo.isEmpty()) {
			String photoPath = FileUpload.uploadFile(photo, request, "photo");
			series.setSCoverPhoto(photoPath);
		}
		boolean bool = seriesService.updateService(series, audioIds);
		return Msg.judge(bool);
	}

	/**
	 * 获取音频系列详情
	 * 
	 * @param sid
	 * @return
	 */
	@GetMapping("/getSeries/{sid}")
	public Msg getSeries(@PathVariable("sid") Integer sid) {

		// 1.根据sid 查询系列表信息
		Series series = seriesService.findById(sid);

		// 2.根据 seriesid 查询出 中间表信息
		List<Seriesandpicbook> findBySid = sapService.findBySid(sid);

		// 3.获取pid 集合
		List<String> pidList = findBySid.stream().map(Seriesandpicbook::getSpPid).collect(Collectors.toList());

		List<Picturebook> pictureList = null;
		// 4.获取绘本信息集合
		if (!pidList.isEmpty()) {
			pictureList = picService.batchFindByIds(pidList);
		}

		return Msg.success().add("series", series).add("picture", pictureList);
	}

	@GetMapping("/exportAudio/{sid}")
	@SuppressWarnings("unused")
	public void exportAudio(@PathVariable("sid") Integer sid, HttpServletResponse response) throws IOException {
		// 1.根据sid 查询系列表信息
		Series series = seriesService.findById(sid);

		// 2.根据 seriesid 查询出 中间表信息
		List<Seriesandpicbook> findBySid = sapService.findBySid(sid);

		// 3.获取pid 集合
		List<String> pidList = findBySid.stream().map(Seriesandpicbook::getSpPid).collect(Collectors.toList());

		List<Picturebook> pictureList = null;
		// 4.获取绘本信息集合
		if (!pidList.isEmpty()) {
			pictureList = picService.batchFindByIds(pidList);
		}

		// 创建poi导出数据对象
		SXSSFWorkbook sxssfWorkbook = new SXSSFWorkbook();
		// 创建sheet页
		Sheet sheet = sxssfWorkbook.createSheet("音频系列详情列表");

		CellRangeAddress region1 = new CellRangeAddress(0, 1, (short) 0, (short) 6);
		// 参数1：起始行 参数2：终止行 参数3：起始列 参数4：终止列
		sheet.addMergedRegion(region1);
		Row headTitle = sheet.createRow(0);
		headTitle.createCell(0).setCellValue("音频系列详情列表");
		Row headRow = sheet.createRow(4);
		headRow.createCell(0).setCellValue("音频系列名称");
		headRow.createCell(1).setCellValue("年龄选项内容");
		headRow.createCell(2).setCellValue("类别选项内容");
		headRow.createCell(3).setCellValue("版权方名称");
		headRow.createCell(4).setCellValue("简介");
		headRow.createCell(5).setCellValue("推荐等级");
		headRow.createCell(6).setCellValue("推荐理由");
		Row dataRow = sheet.createRow(sheet.getLastRowNum() + 1);
		dataRow.createCell(0).setCellValue(series.getSName());
		dataRow.createCell(1).setCellValue(Optional.ofNullable(series.getAge()).orElseGet(Age::new).getAContext());
		dataRow.createCell(2)
				.setCellValue(Optional.ofNullable(series.getCategory()).orElseGet(Category::new).getCContext());
		dataRow.createCell(3)
				.setCellValue(Optional.ofNullable(series.getCopyright()).orElseGet(Copyright::new).getCopyrightname());
		dataRow.createCell(4).setCellValue(series.getSAbstract());
		dataRow.createCell(5).setCellValue(series.getSRdLevel());
		dataRow.createCell(6).setCellValue(series.getSRdreasons());
		Row dataRow3 = sheet.createRow(sheet.getLastRowNum() + 1);
		if (!pidList.isEmpty()) {
			Row headRow2 = sheet.createRow(sheet.getLastRowNum() + 1);
			headRow2.createCell(0).setCellValue("音频名称");
			headRow2.createCell(1).setCellValue("作者");
			headRow2.createCell(2).setCellValue("简介");
			headRow2.createCell(3).setCellValue("出版社");
			headRow2.createCell(4).setCellValue("价格");
			for (Picturebook p : pictureList) {
				Row dataRow2 = sheet.createRow(sheet.getLastRowNum() + 1);
				dataRow2.createCell(0).setCellValue(p.getPName());
				dataRow2.createCell(1).setCellValue(p.getPAuthor());
				dataRow2.createCell(2).setCellValue(p.getPAbstract());
				dataRow2.createCell(3).setCellValue(p.getPPublishing());
				dataRow2.createCell(4).setCellValue(p.getPPrice());
			}
		}
		// 下载导出文件名
		String filename = "音频系列详情列表";
		// 设置头信息
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/vnd.ms-excel");
		// 一定要设置成xlsx格式
		response.setHeader("Content-Disposition",
				"attachment;filename=" + URLEncoder.encode(filename + ".xlsx", "UTF-8"));
		// 创建一个输出流
		ServletOutputStream outputStream = response.getOutputStream();
		// 写入数据
		sxssfWorkbook.write(outputStream);
		// 关闭
		outputStream.close();
		sxssfWorkbook.close();
	}

	/**
	 * 按条件查询音频系列
	 * 
	 * @param ageIds
	 * @param categoryIds
	 * @param copyrightid
	 * @return
	 */
	@PostMapping("/getSeries")
	public Msg getAudioSeries(String sName, int[] ageIds, int[] categoryIds, Integer copyrightid, String flag) {
		List<Series> seriesList = seriesService.getAudioSeries(sName, ageIds, categoryIds, copyrightid, flag);
		return Msg.success().add("series", seriesList);
	}

	/**
	 * 导出音频系列信息
	 * 
	 * @param ageIds
	 * @param categoryIds
	 * @param copyrightid
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 * @throws InvocationTargetException
	 * @throws IllegalArgumentException
	 * @throws IllegalAccessException
	 * @throws NoSuchMethodException
	 */
	@GetMapping("/exportSeries")
	public void exportSeries(String audioName, int[] ageIds, int[] categoryIds, Integer copyrightid,
			HttpServletRequest request, HttpServletResponse response, String flag) throws IOException,
			NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
		List<Series> seriesList = seriesService.getAudioSeries(audioName, ageIds, categoryIds, copyrightid, flag);

		// 创建poi导出数据对象
		SXSSFWorkbook sxssfWorkbook = new SXSSFWorkbook();
		// 创建sheet页
		Sheet sheet = sxssfWorkbook.createSheet("音频系列列表");

		CellRangeAddress region1 = new CellRangeAddress(0, 1, (short) 0, (short) 4);
		// 参数1：起始行 参数2：终止行 参数3：起始列 参数4：终止列
		sheet.addMergedRegion(region1);
		Row headTitle = sheet.createRow(0);
		headTitle.createCell(0).setCellValue("音频系列列表");

		// 创建表头
		Row headRow = sheet.createRow(4);
		// 设置表头信息
		headRow.createCell(0).setCellValue("音频系列名称");
		// headRow.createCell(1).setCellValue("年龄选项内容");
		// headRow.createCell(2).setCellValue("类别选项内容");
		// headRow.createCell(3).setCellValue("版权方名称");
		headRow.createCell(1).setCellValue("简介");
		headRow.createCell(2).setCellValue("推荐等级");
		headRow.createCell(3).setCellValue("推荐理由");

		// 遍历上面数据库查到的数据
		for (Series s : seriesList) {
			Row dataRow = sheet.createRow(sheet.getLastRowNum() + 1);
			dataRow.createCell(0).setCellValue(s.getSName());
			// dataRow.createCell(1).setCellValue(Optional.ofNullable(s.getAge()).orElseGet(Age::new).getAContext());
			// dataRow.createCell(2)
			// .setCellValue(Optional.ofNullable(s.getCategory()).orElseGet(Category::new).getCContext());
			// dataRow.createCell(3)
			// .setCellValue(Optional.ofNullable(s.getCopyright()).orElseGet(Copyright::new).getCopyrightname());
			dataRow.createCell(1).setCellValue(s.getSAbstract());
			dataRow.createCell(2).setCellValue(s.getSRdLevel());
			dataRow.createCell(3).setCellValue(s.getSRdreasons());
		}

		// 下载导出文件名
		String filename = "音频系列列表";
		// 设置头信息
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/vnd.ms-excel");
		// 一定要设置成xlsx格式
		response.setHeader("Content-Disposition",
				"attachment;filename=" + URLEncoder.encode(filename + ".xlsx", "UTF-8"));
		// 创建一个输出流
		ServletOutputStream outputStream = response.getOutputStream();
		// 写入数据
		sxssfWorkbook.write(outputStream);
		// 关闭
		outputStream.close();
		sxssfWorkbook.close();

	}

	/**
	 * 音频系列 - 批量删除
	 * 
	 * @param seriesIds
	 * @return
	 */
	@PostMapping("/deleteSeries")
	public Msg deleteSeries(int[] seriesIds) {
		// 手动开启事物
		DefaultTransactionDefinition def = new DefaultTransactionDefinition();
		def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
		TransactionStatus status = txManager.getTransaction(def);

		boolean batchDelete = seriesService.batchDelete(seriesIds);
		if (!batchDelete) {
			txManager.rollback(status);
			return Msg.fail("删除失败");
		}
		boolean sapbool = sapService.deletePicturesBySids(seriesIds);
		if (!sapbool) {
			txManager.rollback(status);
			return Msg.fail("删除失败");
		}
		txManager.commit(status);
		return Msg.success();
	}

	/**
	 * 类别选项
	 * 
	 * @return
	 */
	@GetMapping("/getAudioCategory")
	public Msg getAudioCategory() {
		List<Category> categoryList = categoryService.getAudioCategory();
		return Msg.success().add("category", categoryList);
	}
}
